package com.oocl.consumer.consumer;

import java.util.ArrayList;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import com.oocl.consumer.dao.BookDao;
import com.oocl.consumer.dao.impl.BookDaoImpl;
import com.oocl.consumer.pojo.Book;

/**
 * 消息队列监听器
 * 
 * @author GANAB
 * 
 */
public class BookMessageListener implements MessageListener {
	private BookDao bookDao = null;
	private int counter = 1;
	private int limit = 5;
	private List<Book> bookList = null;

	public BookMessageListener() {
	}

	public BookMessageListener(int limit) {
		this.bookDao = new BookDaoImpl();
		this.limit = limit;
		this.bookList = new ArrayList<Book>();
	}

	public void onMessage(Message msg) {
		try {
			if ((counter != 0 && counter % limit == 0)) {
				TextMessage textMsg = (TextMessage) msg;
				bookList.add(Book.fromJson(textMsg.getText()));
				// save
				bookDao.addBatchBook(bookList, this.limit);
				// confirm
				msg.acknowledge();
				counter = 1;
				bookList.clear();
			} else {
				// batch add
				TextMessage textMsg = (TextMessage) msg;
				bookList.add(Book.fromJson(textMsg.getText()));
				counter++;
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
